<template>
  <div>
    <a-spin>
      <mt-preview ref="MtPreviewRef" :showPopover="false"></mt-preview>
    </a-spin>
  </div>
</template>
<script setup lang="ts">
import {MtPreview} from 'maotu';
import 'maotu/dist/style.css';
import {useRoute} from "vue-router";
import {onMounted, onUnmounted, ref, inject, watch} from 'vue';
import {getWebtopoProject, getRunTimeList} from '../../../api/webtopo';
import {SocketData} from "@/api/websocketService";

/*************************** 变量区域 begin ***************************/
const props = defineProps({
  projectId: {
    type: String,
    default: "",
  }
});


//路由信息
const route = useRoute();
//项目ID
const projectId = ref<string>('');
//token
const token = ref<string>();
const loading = ref<boolean>(false);
if (route.params) {
  if (route.params.projectId) {
    projectId.value = route.params.projectId.toString();
  }
  if (route.params.token) {
    token.value = route.params.token.toString();
    sessionStorage.setItem("token", token.value);
  }
}
if (props.projectId && props.projectId.length > 0) {
  projectId.value = props.projectId;
}
const MtPreviewRef = ref();
const projectInfo = ref<any>({});
const runTimeList = ref<any>();

const tip = ref<string>("加载中");

/*************************** 变量区域 end ***************************/


/*************************** 方法区域 begin ***************************/


// WebSocket 数据
const {data, sendData}: SocketData = inject('webSocketData', {
  data: {value: 0},
  sendData: () => {
  }
});

// 监听 WebSocket 数据
watch(data, async (newVal) => {
  if (newVal.key && newVal.key.length > 0) {
    console.log("watch=>",newVal)
    changeValue2(newVal);
  }
});

const changeValue2 = (newVal: any) => {
  if (runTimeList.value && runTimeList.value.length > 0) {
    let info: object = {};
    let set_attrs: any = [];

    runTimeList.value.forEach((item: any) => {
      if (item.varSn == newVal.key) {
        info = {
          id: item.svgNodeId,
          key: item.key,
          val: newVal.value.toString()
        };

        set_attrs.push(info);
      }
    })
    console.log("set_attrs=>",set_attrs)
    MtPreviewRef.value?.setItemAttrs(set_attrs);
  }
}

const fetchData = async () => {
  try {
    loading.value = true;
    tip.value = "加载中";
    let res: any = await getWebtopoProject(projectId.value);
    if (res.code == 200) {
      projectInfo.value = res.data;
      if (res.data.dataModel && res.data.dataModel.length > 0) {
        MtPreviewRef.value?.setImportJson(JSON.parse(res.data.dataModel));
      } else {
        MtPreviewRef.value?.setImportJson({
          canvasCfg: {
            width: 1920,
            height: 1080,
            scale: 1,
            color: '#000000',
            img: '',
            guide: true,
            adsorp: true,
            adsorp_diff: 3,
            transform_origin: {
              x: 0,
              y: 0
            },
            drag_offset: {
              x: 0,
              y: 0
            }
          },
          gridCfg: {
            enabled: false,
            align: true,
            size: 10
          },
          json: []
        });
      }
    }
  } catch (err) {
    loading.value = false;
  }
}

/**
 * 获取实时数据
 */
const fetchRunTimeList = async () => {
  try {
    onSubscribe2();
    let res: any = await getRunTimeList(projectId.value);
    if (res.code == 200) {
      console.log("getRunTimeList=>", res.data)
      runTimeList.value = res.data;
      const set_attrs = runTimeList.value.map((item: any) => {
        sendData({
          action: 'subscribe',
          varSn: item.varSn
        });

        return {
          id: item.svgNodeId,
          key: item.key,
          val: item.value
        }
      })
      MtPreviewRef.value?.setItemAttrs(set_attrs);
    }
  } catch (err) {

  }
}

const subscribe2 = () => {
  if (runTimeList.value && runTimeList.value.length > 0) {
    runTimeList.value.forEach((item: any) => {
      sendData({
        action: 'subscribe',
        varSn: item.varSn
      });
    })
  }
}

const onSubscribe2 = () => {
  if (runTimeList.value && runTimeList.value.length > 0) {
    runTimeList.value.forEach((item: any) => {
      sendData({
        action: 'unsubscribe',
        varSn: item.varSn
      });
    })
  }
}

/*************************** 方法区域 end ***************************/

/**
 * 组件卸载
 */
onUnmounted(() => {
  onSubscribe2();
})

onMounted(async () => {
  await fetchData();
  await fetchRunTimeList();
})
</script>
<style scoped></style>